import { http } from '../library/http'

export default {
  namespaced: true,
  state: {
    userinfo: false,
    accessToken: false,
    accessExpire: 0,
    rules: []
  },
  getters: {
    accessToken(state) {
      if (!state.accessToken) {
        state.accessToken = KE.sessionStorage.getString('access_token')
      }
      return state.accessToken
    },
    /**
     * 是否登陆
     */
    isLogin(state, getters) {
      if (!getters.accessToken) {
        return false
      }
      state.userinfo = getters.userinfo
      return KE.timestamp() <= state.accessExpire
    },
    /* 获取保存的用户信息 */
    userinfo(state) {
      let res = KE.jwtInfoGet (state.accessToken)
      if (res === null) {
        return {}
      }
      [state.userinfo, state.accessExpire, state.sign] = res
      return state.userinfo
    },
    /* 当前用户权限 */
    rules(state) {
      state.rules = KE.sessionStorage.getJson('rules')
      return state.rules
    }
  },
  mutations: {
    /**
     * 登陆
     */
    login(state, tok) {
      KE.sessionStorage.setString('access_token', tok)
      state.accessToken = tok
    },
    rule(state, rules) {
      state.rules = rules
      KE.sessionStorage.setJson('rules', rules)
    }
  },
  actions: {
    /**
     * 登录
     */
    login({ state, commit }, data) {
      return new Promise((resolve, reject) => {
        http.post('admin/login', {
          username: data.username,
          password: data.password
        })
          .then(result => {
            if (result.res_code === 0) {
              commit('login', result.token)
              commit('rule', result.rules)
              resolve()
            } else {
              reject(new Error(result.res_msg))
            }
          })
          .catch(reject)
      })
    },
    /**
     * 注销登录
     */
    logout() {
      KE.sessionStorage.remove('access_token')
    }
  }
}
